package com.quick.admin.service;

import com.quick.admin.dao.AdminGoodsDao;
import com.quick.admin.repository.DtsGoodsRepository;
import com.quick.common.dto.DtsGoodsDto;
import com.quick.common.dto.PageDto;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author ：chicunxiang
 * @date ：Created in 2021/2/1 09:10
 * @description：
 * @version: 1.0
 */
@Service
public class AdminProductService {
    @Autowired
    private ElasticsearchTemplate mElasticsearchTemplate;

    @Autowired
    private DtsGoodsRepository mDtsGoodsRepository;

    @Autowired
    private AdminGoodsDao mAdminGoodsDao;

    public PageDto<List<DtsGoodsDto>> getGoods(String content, int page, int pageSize) {
//        Iterable<DtsGoodsDto> all = mDtsGoodsRepository.findAll();
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询

        queryBuilder.withQuery(QueryBuilders.multiMatchQuery(content, "goodsSn", "name", "keywords"))
                .withPageable(PageRequest.of(page - 1, pageSize));
        // 搜索，获取结果
        Page<DtsGoodsDto> search = this.mDtsGoodsRepository.search(queryBuilder.build());
        long totalElements = search.getTotalElements();
        List<DtsGoodsDto> data = search.getContent();
        return new PageDto<>(totalElements, data);
    }

    @PostConstruct
    public void initIndexDBData() {
        // 查询总数
        if (!mElasticsearchTemplate.typeExists("dts_goods", "dts_goods")) {
            mElasticsearchTemplate.createIndex(DtsGoodsDto.class);
            mElasticsearchTemplate.putMapping(DtsGoodsDto.class);
            Integer integer = mAdminGoodsDao.searchGoodsCount();
            // 总数切割.
            if (integer > 100) {
                for (int i = 0; i < integer; i += 100) {
                    List<DtsGoodsDto> dtsGoodsDtos = mAdminGoodsDao.searchGoodsResult(i, 100);
                    System.out.println(dtsGoodsDtos);
                    mDtsGoodsRepository.saveAll(dtsGoodsDtos);
                }
            } else {
                List<DtsGoodsDto> dtsGoodsDtos = mAdminGoodsDao.searchGoodsResult(0, integer);
                mDtsGoodsRepository.saveAll(dtsGoodsDtos);
            }
        }


    }
}
